﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Security.Permissions;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Threading;
using System.Threading;
using System.IO;
using System.Data.SQLite;
/* author: Danny Beaumont
 * This program DOES implement the extra credit (sqlite)
 * watches file modifications  within a given directory and it's subdirectories 
 */
namespace SystemFileWatcher
{
    public partial class form1 : Form
    {
        
        SQLiteConnection sqlite_conn;
        SQLiteCommand sqlite_cmd;
        SQLiteDataReader sqlite_datareader;
        bool txt, exe, dll, rtf, docx;
        FileSystemWatcher watcher = new FileSystemWatcher();
        
        int indexer = 0;
        private bool other;

        public form1()
        {
            Control.CheckForIllegalCrossThreadCalls = false;
            
            // create a new database connection:
            if (File.Exists("database.db"))
                sqlite_conn = new SQLiteConnection("Data Source=database.db;Version=3;New=False;Compress=True;");
            else
            {
                sqlite_conn = new SQLiteConnection("Data Source=database.db;Version=3;New=True;Compress=True;");
                // open the connection:
                sqlite_conn.Open();

                // create a new SQL command:
                sqlite_cmd = sqlite_conn.CreateCommand();
                sqlite_cmd.CommandText = "CREATE TABLE log (id integer primary key, text varchar(30),extension varchar(20));";
                sqlite_cmd.ExecuteNonQuery();
                sqlite_conn.Close();
            }

            // open the connection:
            sqlite_conn.Open();

            // create a new SQL command:
            sqlite_cmd = sqlite_conn.CreateCommand();
            sqlite_cmd.CommandText = "SELECT COUNT(*) FROM log;";
            sqlite_datareader = sqlite_cmd.ExecuteReader();
            if (sqlite_datareader.Read())
            {
                indexer = int.Parse(sqlite_datareader[0].ToString());
                sqlite_datareader.Close();
            }
            sqlite_conn.Close();
            //button1.Enabled = false;
            InitializeComponent();
            button1.Enabled = false;
            StopStripButton.Enabled = false;
            label1.Visible = false;
            extensionBox.Visible = false;
        }
  



        private void WatchButton_Click(object sender, EventArgs e)
        {
            runWatcher();
           
            
            
        }
        [PermissionSet(SecurityAction.Demand, Name="FullTrust")]
        void runWatcher(){
            if (InputText.Text.Length == 0 || !Directory.Exists(InputText.Text))
            {
                InputText.ResetText();
                InputText.AppendText("invalid entry!!");
                WatchButton.Enabled = true;
                button1.Enabled = false;
                StopStripButton.Enabled = false;
                toolStripButton1.Enabled = true;

            }
            else
            {
                WatchButton.Enabled = false;
                toolStripButton1.Enabled = false;
                button1.Enabled = true;
                StopStripButton.Enabled = true;
                watcher = new FileSystemWatcher(InputText.Text);
                if (txt)
                {
                    watcher.Filter = "*.txt";
                }
                if (exe)
                {
                    watcher.Filter = "*.exe";
                }
                if (dll)
                {
                    watcher.Filter = "*.dll";
                }
                if (rtf)
                {
                    watcher.Filter = "*.rtf";
                }
                if (docx)
                {
                    watcher.Filter = "*.docx";
                }
                if (other)
                {
                    watcher.Filter = "*" + extensionBox.Text;
                }
                // Add event handlers.
                watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
                watcher.Changed += new FileSystemEventHandler(OnChanged);
                watcher.Created += new FileSystemEventHandler(OnChanged);
                watcher.Deleted += new FileSystemEventHandler(OnChanged);
                watcher.Renamed += new RenamedEventHandler(OnRenamed);
                
                watcher.IncludeSubdirectories = true;
                watcher.EnableRaisingEvents = true;
                //testing stuff
                
                
                
            }
                
                   
            
        }
        private void OnRenamed(object sender, RenamedEventArgs e)
        {
            sqlite_conn.Open();
            string oldPath = e.OldFullPath;
            string newPath = e.FullPath;
            string statement = "File: " + oldPath + " renamed to " + newPath;
            string[] extension = e.FullPath.Split('.');
            
            textBox1.AcceptsReturn = true;
            indexer++;
            sqlite_cmd.CommandText = "INSERT INTO log (id,text,extension) VALUES ("+(indexer)+",\'"+statement+"\',\'."+extension[extension.Length-1]+"\');";
            sqlite_cmd.ExecuteNonQuery();
            textBox1.AppendText("File: " + oldPath + " renamed to " + newPath + Environment.NewLine);
            sqlite_conn.Close();
            
        }

      

        private void OnChanged(object sender, FileSystemEventArgs e)
        {
            sqlite_conn.Open();
            FileSystemEventArgs events = e;
            string[] fileName = e.Name.Split('.');
            string statement = "File: " + events.Name + " " + events.ChangeType;
            textBox1.AcceptsReturn = true;
            indexer++;
            sqlite_cmd.CommandText = "INSERT INTO log (id,text,extension) VALUES ("+(indexer)+",\'"+statement+"\',\'."+fileName[fileName.Length-1]+"\');";
            sqlite_cmd.ExecuteNonQuery();
            textBox1.AppendText("File: " + events.FullPath + " " + events.ChangeType + Environment.NewLine);
            sqlite_conn.Close();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            {

                watcher.EnableRaisingEvents = false;
                sqlite_conn.Close();
                button1.Enabled = false;
                StopStripButton.Enabled = false;
                // need to group enabling these into a new helper method 
                WatchButton.Enabled = true;
                toolStripButton1.Enabled = true;

            }
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {

            Environment.Exit(0);
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (AboutBox1 box = new AboutBox1())
            {
                box.ShowDialog(this);
            }
        }

        private void queryToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (Form2 dbmt = new Form2())
            {
                dbmt.ShowDialog(this);
            }
        }

        private void comboBox1_SelectedIndexChanged_1(object sender, EventArgs e)
        {
            if (comboBox1.SelectedItem.Equals(".txt"))
            {
                txt = true;
            }else if(comboBox1.SelectedItem.Equals(".rtf"))
            {
                rtf = true;
            }
            else if (comboBox1.SelectedItem.Equals(".dll"))
            {
                dll = true;
            }
            else if (comboBox1.SelectedItem.Equals(".docx"))
            {
                docx = true;
            }
            else if (comboBox1.SelectedItem.Equals(".exe"))
            {
                exe = true;
            }
            else if(comboBox1.SelectedItem.Equals("new"))
            {
                other = true;
                extensionBox.Visible = true;
                label1.Visible = true;
            }

        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            runWatcher();
            WatchButton.Enabled = false;
            toolStripButton1.Enabled = false;
            button1.Enabled = true;
            
        }

        private void StopStripButton_Click(object sender, EventArgs e)
        {
            watcher.EnableRaisingEvents = false;
            sqlite_conn.Close();
            button1.Enabled = false;
            // need to group enabling these into a new helper method 
            WatchButton.Enabled = true;
            toolStripButton1.Enabled = true;

        }    
      
    } 
}

